const { login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");

// 设置cookie的过期时间
function getCookiesExpireTime() {
  const d = new Date();
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000);
  return d.toGMTString();
}

const handleUserRouter = (req, res) => {
  if (req.method === "GET" && req.url === "/login") {
    let { username, password } = req.query;
    // 登录请求
    return login(username, password).then((data) => {
      console.log("data", data.username);
      if (data.username) {
        // let cookie = `username=${username};path:/;httpOnly;expires=${getCookiesExpireTime()};`;
        // 后台给浏览器种植cookie
        // res.setHeader(
        //   "Set-Cookie",
        //   `username=${
        //     data.username
        //   };path:/;httpOnly;expires=${getCookiesExpireTime()};`
        // );
        req.session.username = data.username;
        return new SuccessModel(req.session, "登录成功");
      }
      return new ErrorModel(null, "登录失败");
    });
  }

  // 用来测试登陆后是否带上cookie的接口
  //   if (req.method === "GET" && req.url === "/login-test") {
  //     console.log("cookie", req.cookie.username);
  //     if (req.cookie.username) {
  //       // 说明当前是带着cookie的请求
  //       return Promise.resolve(
  //         new SuccessModel({ username: req.cookie.username }, "登陆成功")
  //       );
  //     } else {
  //       return Promise.resolve(new ErrorModel(null, "登陆失败"));
  //     }
  //   }
};

module.exports = handleUserRouter;
